<template>
    <view>
        <view class="page">
            <swiper class="lists" :current="activeAiIndex" duration="300">
                <swiper-item class="swiper-item" v-for="(item, index) in aiList" :key="index">
                    <chatMsgList
						ref="chatMsgList"
                        id="msgList0"
                        :ai-name="item.name"
                        :ai-index="index"
                        :active-ai-index="activeAiIndex"
                        :welcome="welcome"
                        :user-avatar="userAvatar"
                        :ai-avatar="aiAvatar"
                        :speech-is-open="speechIsOpen"
                        @setMessage="setMessage"
                        @startPlay="startPlay"
                        @stopPlay="stopPlay"
                        @addToPlay="addToPlay"
                        @playAudio="playAudio"
                    ></chatMsgList>
                </swiper-item>
            </swiper>

            <view :class="'box-input ' + (speechIsOpen ? '' : 'no-speech')">
                <view class="btn-model" @tap="switchInputModel">
                    <image v-if="inputModel == 'text'" model="widthFix" src="/others/static/images2/ic_input_audio.png"></image>
                    <image v-else model="widthFix" src="/others/static/images2/ic_input_text.png"></image>
                </view>
                <view v-if="inputModel === 'text'" class="inputsend">
                    <textarea
                        type="text"
                        @input="inputChange"
                        confirm-type="send"
                        @confirm="sendConfirm"
                        placeholder="输入你的问题"
                        :auto-height="true"
                        maxlength="-1"
                        :show-confirm-bar="false"
                        :adjust-position="true"
                        :disable-default-padding="true"
                        cursor-spacing="48rpx"
                        :value="message"
                    ></textarea>
                    <button class="btn-send" @tap="sendText">
                        <image mode="widthFix" src="/others/static/images2/ic_send.png"></image>
                    </button>
                </view>
                <view v-else class="inputsend">
                    <speeching @send="sendAudio" @stopPlay="stopPlay"></speeching>
                </view>
            </view>
            <player ref="player" id="player" @onPlayerEnd="onPlayerEnd"></player>
        </view>
    </view>
</template>

<script>
import { mapGetters } from "vuex";
import chatMsgList from '@/others/components/chatMsgList/chatMsgList.vue';
import speeching from '@/others/components/speeching/speeching.vue';
import player from '@/others/components/player/player.vue';
import { baseURL,version } from "@/config/app";
import { getSetting,getChatSetting } from '@/api/others.js';
const app = getApp();
export default {
    components: {
        chatMsgList,
        speeching,
        player
    },
    data() {
        return {
            userAvatar:'/others/static/images2/ic_user_logo.png',
            aiAvatar: '/others/static/images2/ic_ai_logo.png',
            message: '',
            page_title: '',
            chatSetting: {},
            activeAiIndex: 0,
            index_type: 'diy',
            index_content: '',
            is_check: false,

            welcome: {
                title: '',
                desc: '',
                tips: ''
            },
            aiList: [{name: "wenxin", alias: "智能助手"}],
            notice: {},
            inputModel: 'text',
            speechIsOpen: false,
            playingTextList: [],

            // 待朗读的文本队列
            playingAudioList: [],

            // 待朗读的文本队列
            playingAiIndex: 0,

            playingMsgIndex: 0,
            playingRowIndex: 0,
            playingSi: 0,

            selected: '',
            share_title: '',
            share_image: '',
            ad: ''
        };
    },
	computed: {
	  ...mapGetters(["userInfo"]),
	},
    onLoad() {
		
        this.onLoadClone3389();
    },
    onShow() {
		// const { avatar } = this.userInfo;
		// console.log(avatar,'头像')
		// console.log(this.$store.getters)
		
		// uni.setStorageSync('token','660a6bff75b12136')
		
        if (uni.getStorageSync('userAvatar')) {
			this.userAvatar = uni.getStorageSync('userAvatar');
        }
    },
	onReady(options) { 
	    uni.$on('onPlayerEnd',(data)=>{
			// console.log(data,'onPlayerEnd')
			this.onPlayerEnd()
	    }) 
		
		uni.$on('setMessage',(data)=>{
			// console.log(data,'onPlayerEnd')
			this.setMessage(data)
	    })
		
		uni.$on('startPlay',(data)=>{
			// console.log(data,'startPlay')
			this.startPlay(data)
	    }) 
		
		uni.$on('stopPlay',(data)=>{
			// console.log(data,'stopPlay')
			this.stopPlay()
		}) 
		
		uni.$on('addToPlay',(data)=>{
			// console.log(data,'addToPlay')
			this.addToPlay(data)
		}) 
		
		uni.$on('playAudio',(data)=>{
			// console.log(data,'playAudio')
			this.playAudio(data)
		}) 
	},
	onUnload(){
		console.log('卸载页面')
		this.stopPlay()
		uni.$off('onPlayerEnd')
		uni.$off('setMessage')
		uni.$off('startPlay')
		uni.$off('stopPlay')
		uni.$off('addToPlay')
		uni.$off('playAudio')
	},
    methods: {
        onLoadClone3389(options) {
			getSetting({version:'v1.3.9'}).then(res => {
				this.page_title = res.page_title;
				this.index_type = res.index_type;
				this.speechIsOpen = res.speechIsOpen ? true : false;
				let inputModel = uni.getStorageSync('inputModel');
				this.inputModel = inputModel === 'audio' && res.speechIsOpen ? 'audio' : 'text';
				uni.setNavigationBarTitle({
				    title: res.page_title
				});
				this.getChatSetting();
			});
        },

        sendText() {
			this.stopPlay();
			this.$refs.chatMsgList[this.activeAiIndex].sendText(this.message);
        },

        sendAudio(e) {
			let that = this;
            if (!e.detail) {
                return;
            }
			that.stopPlay()
            const audioFile = e.detail.audioFile;
            const audioLength = e.detail.audioLength;
			
			uni.uploadFile({
			    url: baseURL + '/shopapi/gpt/audio2text',
			    filePath: audioFile,
			    name: 'file',
			    header: {
			        'Content-Type': 'application/x-www-form-urlencoded',
			        'token': that.$store.getters.token,
					'version':version
			    },
			    dataType: 'json',
			    success: function (response) {
			        const res = JSON.parse(response.data);
					// console.log('res',res)
			  //       console.log('text', res.data.text);
			  //       console.log('path', res.data.path);
			        if (!res.data.text) {
			        	uni.showToast({
			        		title:'语音解析失败',
			        		icon:'none',
			        		duration:2000
			        	})
			        	return;
			        }	
			        that.$refs.chatMsgList[0].sendText(res.data.text, res.data.path, audioLength);
			    },
			    fail: function (err) {
					uni.showModal({
					    title: '系统提示',
					    content: '网络错误',
					    showCancel: false,
					    complete: function () {}
					});
			    },
			    complete: function (res) {
			        uni.hideLoading();
			        uni.hideNavigationBarLoading();
			    }
			});
        },

        sendConfirm() {
            setTimeout(() => {
                this.sendText();
            }, 50);
        },

        switchInputModel() {
            let inputModel = this.inputModel === 'audio' ? 'text' : 'audio';
            uni.setStorageSync('inputModel', inputModel);
			this.inputModel = inputModel;
        },

        startPlay(data) {
			this.stopPlay()
            let aiIndex = data.detail.aiIndex;
            let msgIndex = data.detail.msgIndex;
            let subPage = this.$refs.chatMsgList[aiIndex];
            let message = subPage.lists[msgIndex].message;
            if (!message) {
                return;
            }
            subPage.setPlayStart(msgIndex);
            let messageArr = message.split('\n');
            messageArr.forEach((item) => {
                this.$refs.player.addToList(this.trim(item));
            });
            this.$refs.player.addToList('[end]');
			this.playingAiIndex = aiIndex;
			this.playingMsgIndex = msgIndex;
        },

        stopPlay() {
			this.$refs.player.stopPlay()
        },

        onPlayerEnd() {
			let that = this;
            const playingAiIndex = that.playingAiIndex;
            const playingMsgIndex = that.playingMsgIndex;
			that.$refs.chatMsgList[playingAiIndex].setPlayStop(playingMsgIndex);
			that.playingAiIndex = 0;
			that.playingMsgIndex = 0;
        },

        addToPlay(data) {
            const text = this.trim(data.detail.text);
            const aiIndex = data.detail.aiIndex;
            const msgIndex = data.detail.msgIndex;
            if (!text) {
                return;
            }
			this.playingAiIndex = aiIndex;
			this.playingMsgIndex = msgIndex;
            this.$refs.player.addToList(text);
        },

        playAudio(data) {
            let audio = data.detail.audio;
            let aiIndex = data.detail.aiIndex;
            let msgIndex = data.detail.msgIndex;
            if (!audio) {
                return;
            }
            this.$refs.player.playAudio(audio);
			this.$refs.chatMsgList[aiIndex].setPlayStart(msgIndex);
			this.playingAiIndex=aiIndex;
			this.playingMsgIndex=msgIndex;
        },

        inputChange(e) {
            const value = e.detail.value;
			this.message=value;
        },

        setMessage(data) {
			this.message=data.detail;
        },

        trim(str) {
            if (str) {
                str = str.replace(/(^\s*)|(\s*$)/g, '');
            }
            return str;
        },

        getChatSetting() {
			getChatSetting().then(res=>{
				let page_title = this.page_title;
				let desc = res.welcome ? res.welcome : '请输入你的问题';
				let tips = res.tips;
				this.welcome = {
					title: page_title,
					desc: desc ? desc : '',
					tips: tips ? tips : ''
				}
			})
        },
    }
};
</script>
<style>
.page {
    position: absolute;
    width: 100%;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    overflow: hidden;
    background: #f7f7f8;
}


.lists {
    position: absolute;
    left: 0;
    right: 0;
    top: 0rpx;
    bottom: 140rpx;
    width: 100%;
    height: auto;
}

.box-input {
    width: 100%;
    padding: 30rpx 30rpx;
    position: absolute;
    left: 0;
    bottom: 0;
    border-top: 1px solid #eee;
    background: #fff;
    box-sizing: border-box;
}

.box-input .btn-model {
    position: absolute;
    left: 20rpx;
    bottom: 30rpx;
    width: 80rpx;
    height: 80rpx;
    padding: 0;
    border: none;
    border-radius: 10rpx;
    background: none;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9;
}

.box-input .btn-model image {
    width: 48rpx;
    height: 48rpx;
}

.box-input .inputsend {
    width: 590rpx;
    padding: 0;
    position: relative;
    box-sizing: border-box;
    /* box-shadow: 0 0 12rpx rgba(0, 0, 0, 0.1); */
    background: #f7f7f8;
    margin-left: 80rpx;
    border: 1px solid #fff;
    overflow: hidden;
}

.box-input .inputsend textarea {
    width: 500rpx;
    padding: 20rpx 10rpx 20rpx 20rpx;
    border-radius: 10rpx;
    line-height: 40rpx;
    max-height: 800rpx;
    overflow-x: hidden;
    overflow-y: auto;
    color: #4c4d52;
    border: none;
}

.box-input .inputsend .btn-send {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 100rpx;
    height: 80rpx;
    padding: 0;
    border: none;
    border-radius: 10rpx;
    background: none;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9;
}

.box-input .inputsend .btn-send::after {
    display: none;
}

.box-input .inputsend .btn-send:active {
    background: #f2f2f2;
}

.box-input .inputsend .btn-send image {
    width: 40rpx;
}

.no-speech .inputsend {
    width: 690rpx;
    margin-left: 0;
}
.no-speech .btn-model {
    display: none;
}

.empty {
    text-align: center;
    margin: 0 60rpx;
    padding: 80rpx 0 100rpx 0;
    margin-top: 200rpx;
    background: #fff;
    border-radius: 20rpx;
}

.empty image {
    width: 404rpx;
    height: 266rpx;
    margin-bottom: 40rpx;
}

.empty .tip {
    width: 100%;
    line-height: 40rpx;
    font-size: 32rpx;
    letter-spacing: 2rpx;
    color: #444;
}

.btn-finish {
    width: 60%;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 48rpx;
    border: none;
    color: #fff;
    margin: 240rpx auto 0 20%;
    box-shadow: 0 0 20rpx rgba(0, 235, 79, 0.1);
    font-size: 30rpx;
    letter-spacing: 4rpx;
    outline: none;
    background: #39b54a;
    text-align: center;
}

.banner-ad {
    width: 100%;
    height: 120rpx;
    border-top: 2rpx solid #ddd;
}

.content {
    padding: 20rpx;
    background: #fff;
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    box-sizing: border-box;
    overflow: hidden;
    overflow-y: scroll;
}

.content view {
    margin: 10rpx 0;
    word-break: break-all;
    line-height: 1.5;
    font-size: 28rpx;
    color: #444;
}

.content image {
    width: 100%;
}
</style>
